<template>
  <div class="home">
    <div class="home_top">
      <div class="home_top_left" style="color: #fff">
        <span style="color: #fff; font-size: 14px; font-weight: bold">
          作者QQ：1104668682</span>
        <el-button @click="btnShuaxin" style="margin-top: 10px; width: 80px">刷新列表</el-button>
      </div>
      <div class="home_top_right">
        <div style="color: #fff; font-weight: bold">
          <span>用户名：{{ $store.state.userInfo.username }}</span>
          <span style="margin-left: 20px; font-weight: bold" v-if="times">会员到期时间: {{ timestampToTime(times) }}</span>
          <span style="margin-left: 20px; font-weight: bold" v-else>会员到期时间： 暂无会员</span>
        </div>
        <div>
          <el-button @click="btnRevise" style="margin-top: 10px">修改密码</el-button>
          <el-button type="danger" @click="btnLogin" style="margin-top: 10px">退出登陆</el-button>
        </div>
      </div>
    </div>
    <div class="home_list" v-loading="loading">
      <el-table :data="iconlistall" border style="width: 100%" :cell-style="cellStyle">
        <el-table-column
         fixed
          header-align="center"
          align="center"
          prop="prop"
          label="图标"
          width="180"
        >
          <template #default="scope">
            <img :src="scope.row.thumb" alt="" />
          </template>
</el-table-column>
        <el-table-column label="外观名" width="180" align="center">
          <template #default="scope">
            <div class="waiguan" @click="btnUrl(scope.row)">{{ scope.row.info }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="follow" label="关注人数" width="80" align="center" />
        <el-table-column label="公示剩余时间" width="100" align="center">
          <template #default="scope">
            <div style="color: red">{{ time(scope.row.duration) }}</div>
          </template>
        </el-table-column>

        <el-table-column prop="single_unit_price" label="公示售价(元)" align="center" width="100"/>
        <el-table-column prop="sale_price" label="在售售价(元)" width="100" align="center" />
        <el-table-column prop="diff_price" label="差价(元)" width="100" align="center" />
        <el-table-column align="center" label="操作" width="160"  fixed="right">
          <template #default="scope">
            <el-button @click="handleClick(scope.row)" v-if='!scope.row.isShow'>想抢</el-button>
            <el-button v-else @click="handleClick(scope.row)">不想抢</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog v-model="dialogVisible" title="修改密码" width="500">
      <div class="input_title" style="margin-top: 16px; margin-bottom: 6px">
        密码
      </div>
      <div class="input_info">
        <el-input ref="input1" placeholder="请输入密码" v-model="password" maxlength="16" show-password class="mobile-input">
        </el-input>
      </div>
      <div class="input_title" style="margin-top: 16px; margin-bottom: 6px">
        确认密码
      </div>
      <div class="input_info">
        <el-input ref="input1" placeholder="确认密码" v-model="c_password" maxlength="16" show-password
          class="mobile-input">
        </el-input>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="btnVisible"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { post } from '@/utils/request'
import store from '@/store'
import { ElMessageBox } from 'element-plus'
import { shell } from "electron"
let ipcRenderer = require('electron').ipcRenderer
export default {
  data() {
    return {
      tableData: [],
      dialogVisible: false,
      password: '',
      c_password: '',
      times: '',
      loading: true,
      isShow: '',
      info: [],
      id: [],
      ticker:''
    }
  },
  created() {
    let timestamp = Date.parse(new Date())
    let newTime = ''
    newTime = Number(store.state.userInfo.vip_time) * 1000 - timestamp
    if (newTime == 0) {
      this.times = '会员已到期'
    }
    if (newTime > 0) {
      this.times = Number(store.state.userInfo.vip_time) * 1000
      this.timestampToTime(this.times)
    }
  },
  computed: {
    //这里是监听自定义数组的变化 因为有一个计时器每秒都会减去数组中字段的时间 所以 数组是每秒更新的
    iconlistall() {
      return this.tableData
    }
  },
  methods: {
    async getlist() {
      await post(
        `/user/exterior/getCountDownExterior`,
        'application/json;charset=utf-8'
      ).then((res) => {
        if (res.status == '200') {
          this.loading = false
          for (let i = 0, len = res.data.length; i < len; i++) {
            const item = res.data[i]
            item.duration = (item.end_time * 1000 - new Date().getTime()) / 1000
          }
          const consignment_id = this.id.map(i => i.consignment_id)
          res.data.forEach(el => {
            consignment_id.forEach(ed => {
              if (el.consignment_id == ed) {
                el.isShow = true
              }
            })
          });
          this.tableData = res.data //将改变后的数组赋值给自定义的数组 然后调用计时器 每秒减去指定字段的时间戳 -1000毫秒
          if (this.ticker) {
            //这一段是防止进入页面出去后再进来计时器重复启动
            clearInterval(this.ticker)
          }
          this.beginTimer()
        } else if (res.status == '9995') {
          this.loading = false
          ElMessageBox.confirm(
            '抢外观列表只能会员才可展示，开通会员请联系QQ：1104668682',
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消'
            }
          ).then(() => { })
        } else {
          this.loading = false
          this.$message.error(res.info)
          localStorage.removeItem('token')
          store.commit('updatePageType', '')
          this.$router.push('/')
        }
      })
    },
    beginTimer() {
      //这个计时器是每秒减去数组中指定字段的时间
      this.ticker = setInterval(() => {
        for (let i = 0, len = this.tableData.length; i < len; i++) {
          const item = this.tableData[i]
          if (item.end_time * 1000 > new Date().getTime()) {
            item.duration = (item.end_time * 1000 - new Date().getTime()) / 1000
          }else if(item.end_time * 1000 - new Date().getTime()<100){
            this.getlist()
          }
        }
      
      }, 1000)
    },
    time(time) {
      //这个函数是每秒把时间重新计算下
      if (time > 0) {
        let h = ''
        h = Math.floor((time  / 60 / 60) % 24)
        let m = Math.floor((time  / 60) % 60)
        let s = Math.floor((time ) % 60)
        if (h < 10) {
          h = '0' + h
        }
        if (m < 10) {
          m = '0' + m
        }
        if (s < 10) {
          s = '0' + s
        }

        return h + ':' + m + ':' + s
      } else {
        this.getlist()
      }
    },
    timestampToTime(time) {
      // 时间戳为10位需*1000，时间戳为13位的话不需乘1000
      var date = new Date(time)
      let y = date.getFullYear()
      let MM = date.getMonth() + 1
      MM = MM < 10 ? '0' + MM : MM
      let d = date.getDate()
      d = d < 10 ? '0' + d : d
      let h = date.getHours()
      h = h < 10 ? '0' + h : h
      let m = date.getMinutes()
      m = m < 10 ? '0' + m : m
      let s = date.getSeconds()
      s = s < 10 ? '0' + s : s
      return y + '-' + MM + '-' + d
    },

    btnRevise() {
      this.dialogVisible = true
    },
    btnVisible() {
      post(
        `/user/user/update`,
        {
          password: this.password,
          c_password: this.c_password
        },
        'application/json;charset=utf-8'
      ).then((res) => {
        if (res.status == '200') {
          this.$message('密码修改成功')
          this.dialogVisible = false
          // localStorage.setItem('token', res.data.token)
        } else {
          this.$message.error(res.info)
        }
      })
    },
    btnShuaxin() {
      this.getlist()
    },
    btnLogin() {
      ElMessageBox.confirm('是否退出登陆?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        localStorage.removeItem('token')
        store.commit('updatePageType')
        ipcRenderer.send('setStore', 'ticketList', JSON.stringify([]))
        this.$router.push('/')
      })
    },
    btnUrl(el) {
      shell.openExternal(`https://jx3.seasunwbl.com/buyer?appearance_name=${el.info}&t=skin`)
    },
    handleClick(el) {
      el.isShow = !el.isShow
      let ticketListStr = ipcRenderer.sendSync('get-data', 'ticketList') || '[]'
      let arr =  ticketListStr && JSON.parse(ticketListStr)
      if (el.isShow) {
         arr.push(el)
         this.id.push(el)
      } else {
       this.id, arr = arr.filter(function (item) {
          return item.consignment_id !== el.consignment_id
        })
      }
      ipcRenderer.send('setStore', 'ticketList', JSON.stringify(arr))

    },
    //设置字体颜色
    cellStyle(row, column, rowIndex, columnIndex) {
      if (row.row.isShow) {
        return { 'background': '#dbead5' }
      } else {
        return { 'background': '#fff' }
      }
    },
    // btnLogine(el) {
    //   let option = {
    //     title: "小熊抢外观",
    //     body: `您想抢的外观${el.info}，将在两分钟之后进入在售期`
    //   }
    //   new window.Notification(option.title, option)
    // }
  }
}
</script>

<style lang="scss" scoped>
.waiguan {
  color: blue;
  cursor: pointer;
}

.home_top {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #5090f5;
  padding: 10px 20px;
  position: relative;

  .home_top_left {
    font-size: 20px;
    display: flex;
    flex-direction: column;
  }

  .home_top_right {
    cursor: pointer;
    border-radius: 3px;
    padding: 2px;
    display: flex;
    flex-direction: column;
    align-items: end;
  }
}

.home_list {
  padding: 5px 20px;
  margin-top: 20px;
}
</style>
